package com.htu.edu.controller;

import com.htu.edu.bean.User;
import com.htu.edu.common.R;
import com.htu.edu.mapper.UserMapper;
import com.htu.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

// 1. 将该类转换控制器类，并设置该中的方法返回值全部都是json数据
//@Controller
//@ResponseBody
@RestController
// 2. 设置该模块的请求路径，如/user
@RequestMapping("/user")
// 3. 解决跨域
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户id获取用户信息
     * @param userId
     * @return
     */
    @PostMapping("/getUserById")
    public R getUserById(String userId){
        try {
            User user = userService.getUserById(userId);
            if (user != null) {
                return R.error().msg("用户信息已经存在！");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return R.ok();
    }

    @PostMapping("/saveUser")
    public R saveUser(User user)  {
        try {
            int i = userService.saveUser(user);
            if (i > 0) {
                return R.ok().msg("用户信息保存成功！");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return R.error().msg("用户信息保存失败！");
    }

    @PostMapping("/getUserByIdByPass")
    public R getUserByIdByPass(User user){
        try {
            User loginUser = userService.getUserByIdByPass(user.getUserId(), user.getPassword());
            if (loginUser != null) {
                return R.ok().data(loginUser);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return R.ok().msg("用户名或密码错误！");
    }



}
